<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <img v-if="value" :src="value" class="avatar" style="width:100%;height:100%">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'UpLoadImg',
  props: {
    value: {
      type: String,
      default: null
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 < 100

      if (!isJPG || !isPNG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      return isJPG && isLt2M
    },
    uploadImage(data) {
      const cos = new COS({
        SecretId: 'AKID9A0Wt65ta2GYcWCh1BD9IdWGrLjuseU8',
        SecretKey: 'VaecPWSGrFwUplW4SinhPvEICwUWrCQU'
      })
      cos.putObject({
        Bucket: 'tyq-text-1318643386', // 存储桶名称
        Region: 'ap-nanjing', // 地域名称
        Key: data.file.name, // 文件名称
        StorageClass: 'STANDARD', // 固定值
        Body: data.file // 文件对象
      }, (err, data) => {
        if (data.statusCode === 200 && data.Location) {
          this.$emit('input', 'https://' + data.Location)
        } else {
          this.$message.error(err.Message)
        }
      })
    }
  }
}
</script>

<style  lang="scss">
   .avatar-uploader{
          background-color: #f3f6fb;
          width:76px;
          height:76px;
          border:1px dashed #cccccc;
          border-radius: 5px;
          text-align: center;
          line-height: 76px;
        }
</style>
